<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #container {
            margin: 100px auto;
            /* border: 1px solid red; */
            width: 300px;
            height: 340px;
        }
        
        .main {
            position: relative;
            width: 300px;
            height: 300px;
            border: 1px solid lightblue;
        }
        
        .main .box {
            position: absolute;
            top: 0;
            left: 0;
            width: 20px;
            height: 20px;
            background: lightskyblue;
        }
    </style>
</head>

<body>
    <div id="container">
        <div class="main">
            <div class="box">

            </div>
        </div>
        <button class="btn1">开始</button> <button class="btn2">停止</button>
    </div>
    <script>
        // 获取元素
        let start = $(".btn1")[0];
        let end = $(".btn2")[0];

        // 获取大盒子
        let main = $(".main")[0];
        // 获取小盒子
        let box = $(".box")[0];
        let timer;
        start.onclick = function() {
            timer = setInterval(function() {
                if (box.offsetLeft < 280 && box.offsetTop == 0) {
                    box.offsetTop = 0;
                    box.offsetLeft = 0;
                    box.style.left = box.offsetLeft + 10 + "px";
                    console.log(box.offsetLeft);
                }
                if (box.offsetLeft >= 280) {
                    box.offsetLeft = 280;
                    box.offsetTop = 0;
                    box.style.top = box.offsetTop + 10 + "px";
                    console.log(box.offsetTop);

                }
                if (box.offsetTop >= 280) {
                    box.offsetTop = 280;
                    box.offsetLeft = 280;
                    box.style.left = box.offsetLeft - 10 + "px";
                    console.log(box.offsetLeft);
                }
                if (box.offsetTop >= 0 && box.offsetLeft <= 0) {
                    box.offsetLeft = 0;
                    box.offsetTop = 280;
                    box.style.top = box.offsetTop - 10 + "px";
                    console.log(box.offsetTop);
                }


            }, 250);
        };

        end.onclick = function() {
            clearInterval(timer);
        }

        function $(select) {
            return document.querySelectorAll(select);
        }
    </script>
</body>

</html>